package com.mrd.shiptask_shipowner.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.activity.NewsDetailActivity;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.unit_tools.DatasTools;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.flesh_listview.MyListView;
import com.mrd.shiptask_shipowner.unit_tools.flesh_listview.MyListView.OnRefreshListener;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class NewsNotFragment extends Fragment {
	private List<Map<String, Object>> mData;
	private MyAdapter adapter;
	private MyListView listView2;
	private View view;
	private int pageCount = 0;// 总页数
	private int pagePosition = 1;// 当前页数
	private Button upPageB, belowPageB;
	private ProgressDialog progressDialog;

	@SuppressLint("HandlerLeak")
	private Handler handlers = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle data = msg.getData();
			progressDialog.dismiss();
			if (!data.isEmpty()) {
				switch (msg.what) {
				case HttpUrlConstant.GET_MESSAGE_LIST:
					FunctionOfActivity.makeToaskShow(getActivity(),
							data.getString("msg"));
					if (data.getBoolean("ispass")) {
						initListView(view, data.getString("result"));
					}
					break;

				default:
					break;
				}
			}

		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.news_mainifest_completed_main,
				container, false);
		progressDialog = new ProgressDialog(getActivity());
		setInitView(view);
		setInitDatas(pagePosition);
		return view;
	}

	private void setInitView(View view) {
		// TODO Auto-generated method stub
		upPageB = (Button) view.findViewById(R.id.upPageB);
		belowPageB = (Button) view.findViewById(R.id.belowPageB);
		upPageB.setVisibility(View.GONE);
		belowPageB.setVisibility(View.GONE);
		if (pageCount > 1 && pagePosition != 1) {
			upPageB.setVisibility(View.VISIBLE);
		}
		if (pageCount > pagePosition) {
			belowPageB.setVisibility(View.VISIBLE);
		}
		upPageB.setOnClickListener(ocl);
		belowPageB.setOnClickListener(ocl);
	}

	private OnClickListener ocl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.upPageB:
				pagePosition = pagePosition - 1;
				break;
			case R.id.belowPageB:
				pagePosition = pagePosition + 1;
				break;
			default:
				break;
			}
			setInitDatas(pagePosition);

		}
	};

	public void setInitDatas(int pagePosition1) {
		try {
			progressDialog.setMessage("正在刷新，请稍等···");
			progressDialog.show();
			InitDatasDaoImpl.getNewsDatas(getActivity(), "0", pagePosition1
					+ "", handlers);
		} catch (Exception e) {
			progressDialog.dismiss();
		}
	}

	private void initListView(View view, String result) {
		// TODO Auto-generated method stub
		try {
			// 10条数据为一页，与服务端数一致
			JSONObject job = new JSONObject(result);
			String count = DatasTools.getJsonValue(job, "count");
			try {
				pageCount = Integer.parseInt(count) / 10;
			} catch (Exception e) {
			}
			String data = DatasTools.getJsonValue(job, "data");
			JSONArray jas = new JSONArray(data);
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < jas.length(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();

				String mid = DatasTools.getJsonValue(jas.getJSONObject(i),
						"mid");
				String title = DatasTools.getJsonValue(jas.getJSONObject(i),
						"title");
				String time = DatasTools.getJsonValue(jas.getJSONObject(i),
						"time");
				String group = DatasTools.getJsonValue(jas.getJSONObject(i),
						"group");
				String content = DatasTools.getJsonValue(jas.getJSONObject(i),
						"content");
				String action = DatasTools.getJsonValue(jas.getJSONObject(i),
						"action");
				String url = DatasTools.getJsonValue(jas.getJSONObject(i),
						"url");
				map.put("mid", mid);
				map.put("title", title);
				map.put("time", time);
				map.put("group", group);
				map.put("content", content);
				map.put("action", action);
				map.put("url", url);
				mapList.add(map);
			}

			listView2 = (MyListView) view.findViewById(R.id.listView2);
			// 生成动态数组，并且转入数据
			mData = mapList;
			// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
			adapter = new MyAdapter(getActivity());
			listView2.setAdapter(adapter);
			listView2.setonRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					new AsyncTask<Void, Void, Void>() {
						@Override
						protected Void doInBackground(Void... params) {
							try {
								Thread.sleep(2000);
								InitDatasDaoImpl
										.getElectronMainifestDatas(getActivity());
							} catch (Exception e) {
								e.printStackTrace();
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							adapter.notifyDataSetChanged();
							listView2.onRefreshComplete();
						}
					}.execute(null, null, null);
				}
			});
		} catch (Exception e) {
		}
		setInitView(view);
	}

	public final class ViewHolder {
		private TextView newsMessage, newsTime, newsIndex;
		private LinearLayout linearl1;
	}

	public class MyAdapter extends BaseAdapter {

		private final LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({ "NewApi", "ResourceAsColor" })
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder holder = null;

			holder = new ViewHolder();
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.news_listitem, null);
				holder.newsIndex = (TextView) convertView
						.findViewById(R.id.newsIndex);
				holder.newsMessage = (TextView) convertView
						.findViewById(R.id.newsMessage);
				holder.newsTime = (TextView) convertView
						.findViewById(R.id.newsTime);
				holder.linearl1 = (LinearLayout) convertView
						.findViewById(R.id.linearl1);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				holder.linearl1.setBackgroundColor(getResources().getColor(
						R.color.light_gray2));
			} catch (Exception e) {
			}
			holder.newsIndex.setText((position + 1) + "");
			holder.newsMessage.setText(mData.get(position).get("title")
					.toString());
			holder.newsTime.setText(mData.get(position).get("time").toString());
			holder.linearl1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent map = new Intent(getActivity(),
							NewsDetailActivity.class);
					map.putExtra("mid", mData.get(position).get("mid")
							.toString());
					map.putExtra("title", mData.get(position).get("title")
							.toString());
					map.putExtra("time", mData.get(position).get("time")
							.toString());
					map.putExtra("group", mData.get(position).get("group")
							.toString());
					map.putExtra("content", mData.get(position).get("content")
							.toString());
					map.putExtra("action", mData.get(position).get("action")
							.toString());
					map.putExtra("url", mData.get(position).get("url")
							.toString());
					// 添加已读标记跳转false未读
					map.putExtra("type", false);
					startActivity(map);
				}
			});
			return convertView;
		}
	}

}
